﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Shapes;
using PairingMatrix.Common.Enum;
using PairingMatrix.ViewModel;

namespace PairingMatrix.View.Behavior
{
    public class SetZIndexOfProjectCardBehavior : Behavior<ProjectCardControl>
    {
        private ContentPresenter _parent;
        private ProjectCardViewModel _projectCardViewModel;

        protected override void OnAttached()
        {
            AssociatedObject.Loaded += (sender, e) =>
                                       {
                                           _projectCardViewModel = (ProjectCardViewModel) AssociatedObject.DataContext;
                                           _projectCardViewModel.PropertyChanged += ProjectCard_PropertyChanged;
                                           RecalculateZIndex();
                                       };

        }

        void ProjectCard_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if(e.PropertyName == "Position")
            {
                RecalculateZIndex();
            }

            if (e.PropertyName == "ZIndex")
            {
                SetZIndex();
            }
        }

        private void RecalculateZIndex()
        {
            if (_projectCardViewModel.PrimaryCard != null)
            {
                var cardWallViewModel = (ICardWallViewModel)ControlRegistry.CardWallControl.DataContext;
                var primaryCard = cardWallViewModel.ProjectCards.First(p => p.SecondaryProjectCards.Any(SecuritySettings => SecuritySettings.CardNumber == _projectCardViewModel.CardNumber));
                primaryCard.SecondaryProjectCards.ToList().ForEach(sec =>
                                                                   {
                                                                       ControlRegistry.CurrentLatestZIndexOfCards++;
                                                                       sec.ZIndex = ControlRegistry.CurrentLatestZIndexOfCards;
                                                                   });
            }
        }

        private void SetZIndex()
        {
            if (_parent == null)
            {
                _parent = (ContentPresenter)VisualTreeHelper.GetParent(AssociatedObject);
            }

            Canvas.SetZIndex(_parent, _projectCardViewModel.ZIndex);

        }
    }
}
